﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Capokun.Models;
using System.Xml.Serialization;
using System.IO;
using System.Net;
using Capokun.Properties;
using System.Net.Mail;
using System.Configuration;
using Capokun;

namespace Capokun.Controllers
{
	public class HomeController : Controller
	{
		//CapoSongs capoSongs = new CapoSongs();

		public ActionResult Index()
		{
			ViewBag.Message = "Welcome to ASP.NET MVC!";

			return View();
		}

		public ActionResult About()
		{
			return View();
		}

		//public ActionResult SuckSsij()
		//{
		//    List<Song> songsInDb = CapokunContext.GetAllSongs();
		//    ViewBag.Stat = "Songs count in xml: " + songsInDb.Count;

		//    return View();
		//}

		//[HttpPost]
		//[ValidateInput(false)]
		//public ActionResult SuckSsij(SongsModel postSongs)
		//{
		//    List<Song> newSongs = new List<Song>();

		//    try
		//    {
		//        for (int i = 0; i < postSongs.SongTitles.Count(); i++)
		//        {
		//            try
		//            {
		//                Song song = new Song();
		//                song.SongId = cleanTitle(postSongs.SongTitles[i]);
		//                song.Link = postSongs.SongLinks[i];
		//                song.Content = postSongs.SongContents[i];
		//                newSongs.Add(song);

		//                string fileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Songs\\" + song.SongId + ".html";
		//                System.IO.File.WriteAllText(fileName, song.Content, System.Text.Encoding.UTF8);
		//            }
		//            catch (Exception)
		//            {
		//                return View("~/views/shared/Error.cshtml", null);
		//                //return Content("test", "text plain");
		//            }
		//        }


		//    }
		//    catch (Exception)
		//    {
		//        //return Content("test", "text plain");
		//        return View("~/views/shared/Error.cshtml", null);
		//    }

		//    List<Song> currentSongs = CapokunContext.GetAllSongs();

		//    foreach (Song newSong in newSongs)
		//    {
		//        if (!currentSongs.Contains(newSong))
		//        {
		//            currentSongs.Add(newSong);
		//        }
		//    }
		//    ///lets keep this, manually insert into azure table then
		//    SerializeToXML(currentSongs, "CapoSongs.xml");

		//    return View();

		//}

		private string htmlContent(string title, string content)
		{
			///put back the <br/>

			content = content.Replace("\n\n", "<br/>");

			string returned = "";
			//add before
			returned += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
			returned += "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
			returned += "<head>";
			returned += "<title>" + title + "</title>";
			returned += "</head>";
			returned += "<body>";
			returned += "<h1>" + title + "</h1>";
			returned += content;
			//add after
			returned += "</body>";
			returned += "</html>";
			return returned;
		}

		private string cleanTitle(string title)
		{
			title = title.Replace("/", "-");
			title = title.Replace("?", "");
			title = title.Replace("\n", "");
			return title;
		}

        public void SerializeToXML(List<Song> songs, string fileName)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Song>));
            string xmlpath = Server.MapPath(Url.Content("~/Content/" + fileName));
            TextWriter textWriter = new StreamWriter(xmlpath);
            serializer.Serialize(textWriter, songs);
            textWriter.Close();
        }

        //private List<Song> deserializeFromXML(string fileName)
        //{
        //    List<Song> songs = new List<Song>();
        //    string xmlpath = Server.MapPath(Url.Content("~/Content/" + fileName));

        //    if (System.IO.File.Exists(xmlpath))
        //    {
        //        XmlSerializer deserializer = new XmlSerializer(typeof(List<Song>));
        //        TextReader textReader = new StreamReader(xmlpath);
        //        songs = (List<Song>)deserializer.Deserialize(textReader);
        //        textReader.Close();
        //    }
        //    return songs;

        //}

        //public void cleanList()
        //{
        //    List<Song> songs = CapokunContext.GetAllSongs();
        //    Dictionary<string, Song> songsBySongId = new Dictionary<string, Song>();
        //    foreach (Song song in songs)
        //    {
        //        if (!songsBySongId.ContainsKey(song.SongId))
        //        {
        //            songsBySongId[song.SongId] = song;
        //        }
        //    }
        //    List<Song> returnedSongs = songsBySongId.Values.ToList();
        //    SerializeToXML(returnedSongs, "CapoSongs.xml");
        //}

        //public ActionResult Create() { return View(); }

        //[HttpPost]
        //public ActionResult Create(Song submittedSong)
        //{
        //    ///retrieves current temp songs
        //    List<Song> currentTempSongs = deserializeFromXML("CapoSongs_temp.xml");
        //    currentTempSongs.Add(submittedSong);
        //    ///temporarily saves the model, wait for my validation
        //    SerializeToXML(currentTempSongs, "CapoSongs_temp.xml");
        //    /// 
        //    ///send mails to inform admin about new song
        //    //sendMail(submittedSong);

        //    return View("CreateSuccess");
        //}

		//private static void sendMail(Song submittedSong)
		//{
		//    ///send mail to contact
		//    MailMessage mailSender = new MailMessage();
		//    mailSender.To.Add(submittedSong.Contact.EmailAdress);
		//    mailSender.From = new MailAddress(Settings.Default.mailLogin, "Capokun");
		//    mailSender.IsBodyHtml = false;

		//    if (submittedSong.Contact.Language == "fr" || submittedSong.Contact.Language == "fr-FR")
		//    {
		//        mailSender.Subject = "[Capokun] Chanson reçu par Capokun";
		//        mailSender.Body = "Bonjour " + submittedSong.Contact.Name + "," + Environment.NewLine +
		//            "Votre chanson a bien été reçu. Vous recevrez une réponse dès que possible";
		//    }
		//    //else if (language == "en-Gb") default language
		//    else
		//    {
		//        mailSender.Subject = "[Capokun] Song received by Capokun";
		//        mailSender.Body = "Hi, " + submittedSong.Contact.Name + "," + Environment.NewLine +
		//            "Your song was well received. You will get a reply as soons as possible.";
		//    }

		//    ///webmaster@capokun send irwin.lhw@gma that new song was created
		//    MailMessage mail = new MailMessage();
		//    mail.To.Add("irwin.lhw@gmail.com");

		//    mail.From = new MailAddress(Settings.Default.mailLogin, "Server");
		//    mail.Subject = "[Capokun] New song submitted by " + submittedSong.Contact.Name + ": " + submittedSong.Song.SongId;
		//    mail.Body = submittedSong.Contact.Name + " just sent you a new song" +
		//        Environment.NewLine + "His email adress is : " + submittedSong.Contact.EmailAdress;
		//    mail.Body += "<br/><hr/>" + submittedSong.Contact.Message + "<hr/>";
		//    mail.Body += "<a href=\"http://www.capokun.com/home/SongValidate/" + submittedSong.Song.SongId + "\">Link to the new song: " + submittedSong.Song.SongId + "</a>";
		//    mail.IsBodyHtml = true;

		//    SmtpClient client = new SmtpClient(Settings.Default.mailSmtpServer, Settings.Default.mailSmtpServerPort);
		//    client.Credentials = new NetworkCredential(Settings.Default.mailLogin, Settings.Default.mailPassword);
		//    client.Send(mail);
		//    client.Send(mailSender);

		//}

        ///// <summary>
        ///// return temp save song for review
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult SongValidate(string id)
        //{
        //    List<Song> tempSongs = deserializeFromXML("CapoSongs_temp.xml");
        //    Song returnedSong = null;
        //    foreach (Song song in tempSongs)
        //    {
        //        if (song.SongId == id)
        //        {
        //            returnedSong = song;
        //            break;
        //        }
        //    }
        //    return View(returnedSong);
        //}

		[HttpPost]
		///confirm if song was accepted/refused, give reason
		public ActionResult SongValidate(Song submittedSong)
		{
			///temporarily saves the model, wait for my validation


			/// 
			///send mails to inform that song was accepted/ignored
			//sendMail(submittedSong);


			return View("CreateSuccess");
		}

		/// <summary>
		/// if id != null, it means, a specific song is asked, look for it and return it, else returns all songs
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult Songs(string id)
		{
			List<Song> returned = new List<Song>();
			IEnumerable<Song> songs = CapokunContext.GetAllSongs();

			if (string.IsNullOrEmpty(id))
			{
				returned = songs.OrderBy(x => x.SongId).ToList();
			}
			else
			{
				Song returnedSong = null;
				foreach (Song song in songs)
				{
					if (song.SongId == id)
					{
						returnedSong = song;
						returned.Add(returnedSong);
						break;
						
					}
				}
			}
			return View(returned);
		}


		//private Song fixSong(Song returned)
		//{
		//    //returned.Content = returned.Content.Replace("&lt;", "<");
		//    //returned.Content = returned.Content.Replace("&gt;", ">");
		//    returned.Content = HttpUtility.HtmlDecode(returned.Content);
		//    return returned;
		//}

		//public static string replaceAllTheseCaracters(string badString)
		//{
		//    //badString = badString.Replace("&lt;", "<");
		//    //badString = badString.Replace("&gt;", ">");
		//    badString = badString.Replace("<", "&lt;");
		//    badString = badString.Replace(">", "&gt;");
		//    //HtmlString returned = new HtmlString(badString);
		//    return HttpUtility.HtmlDecode(badString);
		//    //return badString;
		//}

		/// <summary>
		/// show all songs
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult Sitemap()
		{
			List<Song> returned = new List<Song>();
			IEnumerable<Song> songs = CapokunContext.GetAllSongs();

			returned = songs.OrderBy(x => x.SongId).ToList();
			return View(returned);
		}
	}
}
